package com.jlwl.houseservice.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jlwl.houseservice.common.Result;
import com.jlwl.houseservice.entity.Feedback;
import com.jlwl.houseservice.service.FeedbackService;
import com.jlwl.houseservice.vo.FeedbackCreateVO;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

/**
 * 用户反馈控制器
 */
@RestController
@RequestMapping("/feedback")
public class FeedbackController {

    @Autowired
    private FeedbackService feedbackService;

    /**
     * 创建反馈
     */
    @PostMapping
    @PreAuthorize("hasRole('USER')")
    public Result<Void> create(@Valid @RequestBody FeedbackCreateVO createVO) {
        // 获取当前用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        
        // 从用户名中提取用户ID（实际项目中应该从UserDetails中获取）
        Integer userId = getUserIdFromUsername(username);
        
        // 创建反馈
        boolean success = feedbackService.createFeedback(createVO, userId);
        if (!success) {
            return Result.error("创建反馈失败");
        }
        
        return Result.success();
    }

    /**
     * 获取用户反馈列表
     */
    @GetMapping
    @PreAuthorize("hasRole('USER')")
    public Result<Page<Feedback>> getUserFeedbacks(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        // 获取当前用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        
        // 从用户名中提取用户ID（实际项目中应该从UserDetails中获取）
        Integer userId = getUserIdFromUsername(username);
        
        Page<Feedback> feedbackPage = feedbackService.getUserFeedbacks(userId, page, size);
        return Result.success(feedbackPage);
    }

    /**
     * 从用户名中提取用户ID
     * 实际项目中应该从UserDetails中获取
     */
    private Integer getUserIdFromUsername(String username) {
        // 这里简化处理，实际项目中应该从UserDetails中获取
        return 1;
    }
} 